<?php

namespace App\Services\Api;

use App\Forms\GoodsAttributeForms;
use App\Forms\GoodsFileForms;
use App\Forms\GoodsForms;
use App\Forms\UserBehaviorForms;
use App\Forms\UserForms;
use App\Models\Good;
use App\Models\GoodsSpu;
use App\Models\UserGoodsBehavior;
use App\Models\UserShareCode;
use App\Plugins\Forms\ShareFreeOrderForms;
use App\Services\BaseServices as Base;

/**
 * Created by lzl
 * Date: 2021 2021/10/9
 * Time: 13:32
 */
class GoodsServices extends Base
{

    /**
     * @param $validated
     * @return mixed
     */
    public function getList($validated)
    {
        $validated['status'] = Good::ON_SALE;

        $goodsList = (new GoodsForms())->getGoodsList($validated, Good::LIST_FIELD);

        $goodsList =  filled($goodsList) ? (new GoodsAttributeForms())->setSkuAmount($goodsList->toArray()) : $goodsList;

        return $goodsList;
    }


    /**
     * 商品详情
     * @param $goods_id
     * @return array
     * @throws \App\Exceptions\RequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     */
    public function getDetail($goods_id)
    {
        //商品基础信息
        $goodsForms = new GoodsForms();
        $goods = $goodsForms->getGoodsSkuDetail($goods_id);

        //分享海报
        $userForms = new UserForms();
        $share_image = $userForms->getUserShareSingle([
            'uid'      => UID,
            'type'     => UserShareCode::GOODS_SHARE,
            'goods_id' => $goods_id
        ]);

        if(blank($share_image)){

            $url = (new ShareCodeServices())->generateGoodsImage(
                $goodsForms->getGoodsDetail($goods_id),
                $userForms->getUserDetail(UID),
                $goods['sku'][0]['price'],
                $goods['sku'][0]['market_price']
            );

            $share_image = $userForms->createUserShareCode([
                'uid'      => UID,
                'type'     => UserShareCode::GOODS_SHARE,
                'goods_id' => $goods_id,
                'url'      => $url
            ]);

        }

        $goods['share_image'] = $share_image->url;

        $goods['is_collect']  = (new UserBehaviorForms())->checkBehavior($goods_id, UID,UserGoodsBehavior::COLLECT);
        $goods['spu'] = GoodsSpu::where('goods_id', $goods_id)->get();

        //图片信息
        $file = (new GoodsFileForms())->getGoodsFile($goods_id);

        //增加用户浏览记录
        (new UserBehaviorForms())->setBehavior($goods_id, UID, UserGoodsBehavior::BROWSE);

        return compact('goods', 'file');
    }


    public function getCategory($validated)
    {

    }

}